<template>
  <div class="app-container">
    <!-- 台账审批 -->
    <el-card shadow="hover" class="flex1 h" v-loading="loading">
      <template #header>
        <div class="disf jub alc">
          台账审批
          <div v-if="isAudit">
            <el-button type="success" @click="handleApprove(1)">通 过</el-button>
            <el-button type="danger" @click="handleApprove(2)">驳 回</el-button>
          </div>
        </div>
      </template>
      <div class="disf dirc h pr30">
        <el-form label-width="100px">
          <el-form-item label="合同名称">
            {{ ledger?.contractName }}
          </el-form-item>
          <el-form-item label="修改原因">
            {{ ledger?.title || "-" }}
          </el-form-item>
          <el-form-item label="申请人">
            {{ ledger?.username }}
          </el-form-item>
          <el-form-item label="申请时间">
            {{ ledger?.createTime }}
          </el-form-item>
          <el-form-item label="状态">
            {{ (ledger?.status && ContractLedger_Status_Label[ledger.status]) || "-"
            }}{{ ledger?.remark && "，审批建议：" + ledger.remark + "。" }}
          </el-form-item>
          <el-form-item label="项目台账">
            <el-table
              v-if="contractItems.length"
              ref="dataTableRef"
              :data="contractItems"
              height="40vh"
              :cell-class-name="handleLineClass"
            >
              <el-table-column label="变更" align="center" width="60">
                <template #default="scope">
                  <el-icon :color="scope.row.operation === 3 ? 'red' : 'green'">
                    <Plus v-if="scope.row.operation === 1" />
                    <EditPen v-if="scope.row.operation === 2" />
                    <Minus v-if="scope.row.operation === 3" />
                  </el-icon>
                </template>
              </el-table-column>
              <el-table-column label="材料类型" align="center" width="90">
                <template #default="scope">
                  {{ SaleMealTypeLabel[scope.row.itemType] }}
                </template>
              </el-table-column>
              <el-table-column label="材料名称" prop="name" width="200" />
              <el-table-column label="规格" prop="spec" />
              <el-table-column label="单位" prop="unit" align="center" width="80" />
              <el-table-column label="数量" align="center" prop="quantity" width="100">
                <template #default="scope">
                  <div v-if="scope.row.operation === 2 && scope.row.originalItem.quantity">
                    <del>{{ scope.row.originalItem.quantity }}</del>
                    &nbsp;
                    <span style="color: red">{{ scope.row.quantity }}</span>
                  </div>
                  <span v-else>{{ scope.row.quantity }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单价" align="center" prop="price" width="180">
                <template #default="scope">
                  <div v-if="scope.row.operation === 2 && scope.row.originalItem.price">
                    <del>{{ `￥${scope.row.originalItem.price}` }}</del>
                    &nbsp;
                    <span style="color: red">{{ `￥${scope.row.price}` }}</span>
                  </div>
                  <span v-else>{{ `￥${scope.row.price}` }}</span>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无数据"></el-empty>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- 弹窗：审批 -->
    <el-dialog
      v-model="dialogApprove.visible"
      :title="dialogApprove.title"
      width="500px"
      @close="closeApprove"
    >
      <el-form ref="roleFormRef" :model="formData" label-width="100px" label-position="top">
        <el-form-item label="审批建议" prop="remark">
          <el-input
            type="textarea"
            :rows="3"
            v-model="formData.remark"
            placeholder="请输入审批建议"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmitApprove">确 定</el-button>
          <el-button @click="closeApprove">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { decryptDES } from "@/utils/des";
import ContractLedgerAPI, {
  ContractLedger_Status_Label,
  ContractLedgerApproveForm,
  ContractLedgerRecordAndLast,
  ContractLedgerRecordCompare,
} from "@/api/flow/contractLedger.api";
import { cloneDeep } from "lodash-es";
import { SaleMealTypeLabel } from "@/api/business/material/sealMeal.api";

const route = useRoute();

const id = ref(""); // 合同id
const recordId = ref(""); // 记录id
const isAudit = ref(false); // 是否审核
// const contractBuild = ref<BuildDetailVO>(); // 合同施工详情
const ledger = ref<ContractLedgerRecordAndLast>();
const newMeals = ref<ContractLedgerRecordCompare[]>([]); // 最新材料列表
const oldMeals = ref<ContractLedgerRecordCompare[]>([]); // 上次材料列表
const contractItems = ref<ContractLedgerRecordCompare[]>([]); //合同材料变动列表

// 审批表单
const formData = reactive<ContractLedgerApproveForm>({
  recordId: "",
  status: 1,
  remark: "",
});

const loading = ref(false);

watch(
  () => route.query.key,
  async (val) => {
    // 提取转换密文对象
    const str = decryptDES(val as string);
    const busiInfo = JSON.parse(str) || {}; //业务信息
    id.value = busiInfo.id;
    recordId.value = busiInfo.recordId;

    // 获取实例id和对比
    await loadBase();
  },
  {
    immediate: true,
  }
);

// 加载基础信息
async function loadBase() {
  loading.value = true;
  try {
    ledger.value = await ContractLedgerAPI.loadCompareByRecordId(recordId.value);
    newMeals.value = ledger.value.currentItems;
    oldMeals.value = ledger.value.lastItems;
    formData.recordId = ledger.value.id;
    isAudit.value = ledger.value.status === 0;
    compareData();
  } catch (error) {
    console.log(error);
  }
  loading.value = false;
}

/**
 * 对比变动数据
 */
function compareData() {
  newMeals.value.forEach((m) => {
    const compItem: ContractLedgerRecordCompare = cloneDeep(m);
    const oldItem = oldMeals.value.find((o) => o.resourceId === m.resourceId);
    if (!oldItem) {
      // 1-新增
      compItem.operation = 1;
    } else {
      // 2-修改
      const listenParams = ["quantity", "price"]; //监听参数
      listenParams.forEach((param) => {
        if (m[param] != oldItem[param]) {
          compItem.operation = 2;
          compItem.originalItem ||= {}; //变动项原始值
          compItem.originalItem[param] = oldItem[param];
        }
      });
    }
    contractItems.value.push(compItem);
  });
  oldMeals.value
    ?.filter((m) => {
      return !newMeals.value.some((n) => n.resourceId === m.resourceId);
    })
    .forEach((item) => {
      const compItem: ContractLedgerRecordCompare = { ...item, operation: 3 };
      contractItems.value.push(compItem);
    });
}

// 行样式
function handleLineClass({ row }: ContractLedgerRecordCompare) {
  if (row.operation === 1) {
    return "add";
  }
  if (row.operation === 3) {
    return "delete";
  }
  return "";
}

/**
 * 审批弹窗
 */
const dialogApprove = reactive<{
  visible: boolean;
  title: string;
}>({
  visible: false,
  title: "",
});

function handleApprove(status: number) {
  dialogApprove.visible = true;
  dialogApprove.title = status == 1 ? "审批通过" : "审批驳回";
  formData.remark = status == 1 ? "审核通过" : "";
  formData.status = status;
}

function closeApprove() {
  dialogApprove.visible = false;
}

function handleSubmitApprove() {
  if (!formData.remark) {
    ElMessage.warning("请填写审批建议");
    return;
  }
  ContractLedgerAPI.approval(formData)
    .then(() => {
      ElMessage.success("审批完成");
      closeApprove();
    })
    .catch((error) => {
      console.error(error.message);
    });
}
</script>

<style lang="scss" scoped>
:deep(.el-card__body) {
  height: calc(100% - 70px);
}

:deep(.el-table__body td.el-table__cell) {
  &.add {
    background-color: #daffc6;
  }
  &.delete {
    background-color: #ffd3d3;
  }
}
</style>
